package com.example.textroom.data.repository;

import android.content.Context;

import androidx.lifecycle.LiveData;

import com.example.textroom.app.UserDatabase;
import com.example.textroom.bead.Word;
import com.example.textroom.data.dao.WordDao;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WordRepository {
    private final LiveData<List<Word>> allWordsLive;
    private final WordDao wordDao;
    ExecutorService executorService = Executors.newFixedThreadPool(1);  // 线程池

    public WordRepository(Context context) {
        // 使用单例模式获取到数据库实例
        UserDatabase wordDatabase = UserDatabase.getDatabase(context.getApplicationContext());
        wordDao = wordDatabase.getWordDao();
        allWordsLive = wordDao.getAllWordsLive();  // 该操作不用启动后台线程，或放到线程池中去执行

    }

    public LiveData<List<Word>> getAllWordsLive() {
        return allWordsLive;
    }

    public void insertWords(Word... words){
        executorService.submit(() -> wordDao.insertWords(words));
    }

    public void deleteWords(Word... words){
        executorService.submit(() -> wordDao.deleteWords(words));
    }
    public void updateWords(Word... words){
        executorService.submit(() -> wordDao.updateWords(words));
    }
    public void deleteAllWords(){
        // executorService.submit(() -> wordDao.deleteAllWords());
        // submit 方法的参数，能够进一步简写为下面的 Lambda 表达式
        executorService.submit(wordDao::deleteAllWords);
    }
}
